import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/extension_util.dart';

import '../style/app_style.dart';

///倒计时的按钮（例如发送验证码的按钮）
class TimerButton extends StatefulWidget {
  ///倒计时时间
  final int timeClock;

  ///按钮初始文本
  final String originalButtonText;

  ///按钮点击后再重新恢复后的文本
  final String retryButtonText;

  ///点击执行的操作
  final Future<bool> Function() onTap;

  ///计时器是否有用
  final bool isEnable;

  const TimerButton({
    Key? key,
    this.timeClock = 60,
    this.originalButtonText = "get_code",
    this.retryButtonText = "regain",
    required this.onTap,
    this.isEnable = true,
  }) : super(key: key);

  @override
  State<TimerButton> createState() => TimerButtonState();
}

class TimerButtonState extends State<TimerButton> {
  late Timer _timer;
  late int timeClock;

  ///我是干净的，点击之后，我不干净了
  bool _iAmClean = true;

  ///正在倒计时
  late bool isRunning;

  @override
  void initState() {
    _timer = Timer(const Duration(seconds: 1), () {});
    isRunning = false;
    timeClock = widget.timeClock;
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  void sendRuning() {
    isRunning = true;
    setState(() {});
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      timeClock--;
      setState(() {});
      if (timeClock == 0) {
        timeClock = widget.timeClock;
        isRunning = false;
        _iAmClean = false;
        timer.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ()async {
        if(!isRunning && widget.isEnable){
          var res = await widget.onTap();
          if(res == true){
            sendRuning();
          }
        }
      },
      child:

      Container(
        decoration: BoxDecoration(
          border: Border.all(
            color: AppColor.textColor,
            width: 0.5,
          ),

        ),
        height: double.infinity,
        alignment: Alignment.center,
        child: isRunning == false
            ?
        Text(
                _iAmClean == true
                    ? widget.originalButtonText.tr
                    : widget.retryButtonText.tr,
                style:  TextStyle(
                    color:  AppColor.textColor, fontSize: 9.5.sp),
              )
        // AppButton.fullBtn(() { }, "get_code".tr,isEnable: false,style: AppButtonStyle.hollowBlack,padding: EdgeInsets.zero,textStyle: TextStyle(color: true ? AppColor.textColor1 : AppColor.textColor, fontSize: 9.5.sp))
            : Text(
                 "${timeClock}s",
                style: TextStyle(
                    color: AppColor.textColor, fontSize: 9.5.sp),
              ),
      ),
    );
  }
}
